//
//  HomeTableViewController.swift
//  SinaWeibo
//
//  Created by 林柱强 on 16/1/28.
//  Copyright © 2016年 林柱强. All rights reserved.
//  App Key：112547438
//  App Secret：a404475e2a5dd3065a2477c0b03fa6f7
//  授权回调页：http://www.baidu.com

import UIKit
import SVProgressHUD

//定义首页标识符
private let HomeTableViewReuseIdentifier = "HomeTableViewReuseIdentifier"

class HomeTableViewController: BaseTableViewController {

    
    
    //数据源 模型数组
    var statuses: [Status]? {
        didSet{
            //设置完毕数据就刷新表格
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !userLogin {
            visitorLoginView?.setUIInfo(nil, tittle: "关注一些人，回这里看看有什么惊喜")
            return
        }
        //
        setupNav()
        //准备tableView
        prepareTableView()
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "showPhotoBrowser:", name: StatusPictureViewSelected, object: nil)
        
        
        //获取网络
        loadData()
    }
    /**
     显示图片浏览器
     */
    func showPhotoBrowser(notify: NSNotification) {
//        print(notify.userInfo)
        //使用通知传数据时，要判断数据是否存在
        guard let indexPath = notify.userInfo![StatusPictureViewIndexKey] as? NSIndexPath  else {
            return
        }
        
        guard let urls = notify.userInfo![StatusPictureViewURLsKey] as? [NSURL] else {
            return
        }
        //创建图片浏览器
        print(indexPath.item, urls)
        let vc = PhotoBrowserController(index: indexPath.item, url: urls)
        //显示图片浏览器
        presentViewController(vc, animated: true, completion: nil)
    }
    
    private func prepareTableView() {
        //设置下拉刷新
        refreshControl = HomeRefreshControl()
        
        //添加下拉刷新监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
        
        //注册Cell
        tableView.registerClass(StatusTableViewCell.self, forCellReuseIdentifier: HomeTableViewReuseIdentifier)
        tableView.registerClass(StatusOriginalTableViewCell.self, forCellReuseIdentifier: StatusTableViewCellIdentifier.OriginalCell.rawValue)
        tableView.registerClass(StatusForwardTableViewCell.self, forCellReuseIdentifier: StatusTableViewCellIdentifier.ForwardCell.rawValue)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
    
    /// 定义变量记录当前是上拉还是下拉
    var pullupRefreshFlag = false
    //MARK: 加载微博首页数据
    @objc private func loadData() {
        //确定since_id
        //注意 如果max_id 和 since_id同时有值 服务器不会给任何数据
        // 1.默认当做下拉处理
        var since_id = statuses?.first?.id ?? 0
        
        var max_id = 0
        // 2.判断是否是上拉
        if pullupRefreshFlag
        {
            since_id = 0
            max_id = statuses?.last?.id ?? 0
        }
        //加载数据
        Status.loadStatuses(
            since_id, max_id: max_id) { (models, error) -> () in
            
            print(models?.count)
            self.refreshControl?.endRefreshing()
            
            if models == nil {
                //请求失败
//                SVProgressHUD.showErrorWithStatus("暂未有新微博")
//                SVProgressHUD.showInfoWithStatus("暂未有新微博")
                //加载数据失败 停止动画
                self.showNewStatusCount(models?.count ?? 0)
                return
            }
            //到这里一定会拿到数据
            if since_id > 0 {
                //下拉刷新 直接追加数据
                self.statuses = models! + self.statuses!
                self.showNewStatusCount(models?.count ?? 0)
            }else if max_id > 0 {
                //上拉加载更多数据
                self.statuses = self.statuses! + models!
                //加载数据完成,停止动画
            } else {
                //首次加载
                self.statuses = models
            }
            
        }
    }
    /**
     显示刷新提醒
     */
    private func showNewStatusCount(count: Int) {
        newStatusLabel.hidden = false
        newStatusLabel.text = (count == 0 ) ? "木有新的微博数据" : "刷新了\(count)条微博"
        
        //执行动画
        UIView.animateWithDuration(2, animations: { () -> Void in
            self.newStatusLabel.transform = CGAffineTransformMakeTranslation(0, self.newStatusLabel.frame.height)
            }, completion: { (_) -> Void in
                UIView.animateWithDuration(2, animations: { () -> Void in
                    self.newStatusLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.newStatusLabel.hidden = true
                })
        })

    }
    
    /**
     修改标题按钮的状态
     */
    func change(){
        // 修改标题按钮的状态
        let titleBtn = navigationItem.titleView as! TitleButton
        titleBtn.selected = !titleBtn.selected
    }
    /**
     初始化导航条
     */
    private func setupNav()
    {
        // 1.初始化左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem.creatBarButtonItem("navigationbar_friendsearch", target: self, action: "leftItemClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem.creatBarButtonItem("navigationbar_pop", target: self, action: "rightItemClick")
        
        // 2.初始化标题按钮
        let titleBtn = TitleButton()
        titleBtn.setTitle(UserAccount.loadAccount()?.screen_name ?? "", forState: UIControlState.Normal)
        titleBtn.addTarget(self, action: "titleBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    func titleBtnClick(btn: TitleButton)
    {
        // 2.弹出菜单
        let sb = UIStoryboard(name: "PopoverViewController", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        // 2.1设置转场代理
        vc?.transitioningDelegate = popverAnimator
        
        // 2.2设置转场的样式
        vc?.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc!, animated: true, completion: nil)
        
    }
    
    func leftItemClick()
    {
        print(__FUNCTION__)
    }
    
    func rightItemClick()
    {
        let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        presentViewController(vc!, animated: true, completion: nil)
    }
    
    //MARK: 懒加载控件
    // 一定要定义一个属性来报错自定义转场对象, 否则会报错
    private lazy var popverAnimator:PopoverAnimator = {
        let pa = PopoverAnimator()
        pa.presentFrame = CGRect(x: 100, y: 56, width: 200, height: 350)
        return pa
    }()
    
    private lazy var newStatusLabel: UILabel = {
       let label = UILabel()
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        label.font = UIFont.systemFontOfSize(14)
        
        let height:CGFloat = 44
        label.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 44)
        //添加到导航栏下方
        
        label.hidden = true
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
    }()
    
    /// 微博行高的缓存, 利用字典作为容器. key就是微博的id, 值就是对应微博的行高
    var rowCache: [Int: CGFloat] = [Int: CGFloat]()
    
    override func didReceiveMemoryWarning() {
        // 清空缓存
        rowCache.removeAll()
    }
}

//定义extension  包含了所有的数据源方法 和协议方法
extension HomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = statuses![indexPath.row]
        // 1.获取cell
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusTableViewCellIdentifier.cellID(status), forIndexPath: indexPath) as! StatusTableViewCell
        
        // 2.设置数据
        
        cell.status = status
        
        // 3.判断是否滚动到了最后一个cell
        let count = statuses?.count ?? 0
        if indexPath.row == (count - 1) {
            pullupRefreshFlag = true
            loadData()
            print("静默加载数据")
            pullupRefreshFlag = false
        }
        return cell
    }
    
    // 返回行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 1.取出对应行的模型
        let status = statuses![indexPath.row]
        
        // 2.判断缓存中有没有
        if let height = rowCache[status.id]
        {
            return height
        }
        
        // 3.拿到cell
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusTableViewCellIdentifier.cellID(status)) as! StatusTableViewCell
        
        // 4.拿到对应行的行高
        let rowHeight = cell.rowHeight(status)
        
        // 5.缓存行高
        rowCache[status.id] = rowHeight
        
        // 6.返回行高
        return rowHeight
    }
}
